/*
 * FileMerger.cpp
 *
 *  Created on: Oct 10, 2012
 *      Author: bruno
 */


#include "FileMerger.h"

FileMerger::FileMerger() :
	output()
{
	inputs = new std::vector<IDS_ptr>();
}

FileMerger::~FileMerger()
{
//	delete output;
//	for (unsigned int i = 0; i < inputs->size(); i++) {
//		delete inputs->at(i);
//	}
	delete inputs;
}

void FileMerger::addinput(IDS_ptr &storage)
{
	inputs->push_back(storage);
}

void FileMerger::setOutput(IDS_ptr &storage)
{
	output = storage;
}

void FileMerger::mergeFiles()
{
	Heap<MergeProcessEntry, mergeProcessEntryComparator> heap( inputs->size() );

	for ( unsigned int i = 0; i < inputs->size(); i++ )
	{
		IDS_ptr input = inputs->at(i);

		DICTIONARY_ENTRY entry = input->get();

#ifdef DEBUG
		cout << endl << "loading:" << entry->getRandomKey();
#endif

		heap.loadItem( MergeProcessEntry(input, entry) );
	}

	heap.heapify();

	do {

		MergeProcessEntry entry = heap.peekItem();

		if ( entry.storage->hasNext() )
		{

			MergeProcessEntry newEntry(entry.storage, entry.storage->get());

			entry = heap.pushAndPopItem(newEntry);

		} else {

			entry = heap.popItem();

		}

		output->put(entry.value);

	} while (heap.lenght() > 0);

	output->close();
}

void FileMerger::clearInputs(){

	inputs->clear();

}

int mergeProcessEntryComparator(MergeProcessEntry entry1, MergeProcessEntry entry2) {
	int result = entry1.value->getRandomKey() - entry2.value->getRandomKey();
	if (result == 0) {
		result = strcmp(entry1.value->getTerm(), entry2.value->getTerm());
	}
	return result;
}

